package com.wantong.jianpu.net;

import com.wantong.jianpu.utils.XUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import me.goldze.mvvmhabit.utils.ToastUtils;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @author PACY
 * @date 2022/6/6
 * description:
 */
public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            try {
                String result = buffer.clone().readString(StandardCharsets.UTF_8);
                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.getInt("code");
                if (code == 401) {//判断返回code
                    ToastUtils.show("身份过期，请重新登录");
                    XUtils.toLoginPage();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}
